// 文件路径: src/main/java/com/example/demo22/interceptor/LoginInterceptor.java

package com.example.demo22.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String uri = request.getRequestURI();

        // 放行指定路径
        if ("/login".equals(uri) || "/register".equals(uri) || "/forgotPassword".equals(uri) || uri.startsWith("/static/")) {
            return true;
        }

        HttpSession session = request.getSession();
        Object user = session.getAttribute("user");

        if (user == null) {
            response.sendRedirect("/login");
            return false;
        }

        return true;
    }
}
